package vip.ola.pay.batchpay.telbatchpay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.ola.core.common.util.IPUtility;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.AgentpayPassageAccount;
import vip.ola.core.entity.TransOrder;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.mq.BaseNotify4MchTrans;
import vip.ola.pay.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_COMPLETE;
import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_SUCCESS;

@RequestMapping("/api/telpay")
@Controller
public class TelpayTransController extends BaseController {

    private static final MyLog _log = MyLog.getLog(TelpayTransController.class);

    @Autowired
    private RpcCommonService rpcCommonService;

    @Autowired
    public BaseNotify4MchTrans baseNotify4MchTrans;

    @PostMapping("/notify")
    @ResponseBody
    public String notify(@RequestParam Map<String,String> object, HttpServletRequest request){
        _log.info("接收TelpayTransController回调：" + object);
        // 判断请求IP是否允许+"："
        String clintIp = IPUtility.getClientIp(request);
        _log.info("请求ip为：" + clintIp);
        boolean isAllow = PayUtil.ipAllow(clintIp, "206.119.88.246", "");
        if (!isAllow) {
            _log.info( "IP[" + clintIp + "]不允许访问");
            return "ip fail";
        }
        String transOrderId = object.get("sh_order");
        TransOrder payOrder = rpcCommonService.rpcTransOrderService.findByTransOrderId(transOrderId);
        BigDecimal orderMoney = BigDecimal.valueOf(Double.valueOf(object.get("actual_price")));
        if (orderMoney.longValue() != payOrder.getAmount()/100){
            return "money fail";
        }
        if(payOrder == null){
            return "order not exist!";
        }
        if (payOrder.getStatus() == TRANS_STATUS_SUCCESS || payOrder.getStatus() == TRANS_STATUS_COMPLETE) {
            return "success";
        }
        AgentpayPassageAccount payPassageAccount = rpcCommonService.rpcAgentpayPassageAccountService.findById(payOrder.getPassageAccountId());
        if(payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())){
            return "fail";
        }
        JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
        String retSign = object.get("sign");
        String privateKey = accountParams.getString("privateKey");
        String sign =getSign(object, privateKey);
        _log.info("加签信息：map-{},sign->{}", object, sign );
        if (retSign.equals(sign)){
            if ("4".equals(object.get("state"))){
                String channelOrderNo = object.get("pt_order");
                int result =  rpcCommonService.rpcTransOrderService.updateStatus4Success(transOrderId, channelOrderNo);
                _log.info("更新订单状态为支付成功: result={}", result);
                if(result == 1){
                    // 通知业务系统
                    baseNotify4MchTrans.doNotify(payOrder, true);
                    return "success";
                }
            }else {
                    _log.info("orderStatus error");
            }

        }else {
            _log.info("sign error");
        }
        return "fail!";
    }

    private String getSign(Map<String,String>object, String privateKey) {
        SortedMap<String,String> map = new TreeMap<>(object);
        map.remove("sign");
        // 生成签名
        StringBuffer paramstr = new StringBuffer();
        for (String pkey : map.keySet()) {
            String pvalue = map.get(pkey);
            if (pvalue != null && pvalue != "") {
                paramstr.append(pkey + "=" + pvalue + "&");
            }
        }
        String paramsrc = paramstr.substring(0, paramstr.length() - 1);
        StringBuffer strbuff = new StringBuffer();
        strbuff.append(paramsrc + "&key=" + privateKey);
        String sign = null;
        try {
            sign = PayDigestUtil.md5(strbuff.toString(), "UTF-8");
            _log.info("签名:" + sign);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sign;
    }


}
